<?php
/**
 * Created by PhpStorm.
 * User: Guangpeng Chen
 * Date: 15-5-12
 * Time: 下午6:46
 * 营销活动订单
 */
class MarketingOrder extends DisOrder {
    const IS_SALE = 1;//表示零售
    public function order($option, $aid = 0, $dataMark)
    {
        $s = $this->s;
        $this->option = $option;
        $member = $this->m->memberID;
        $pid = $this->p->pid;

        $begintime = $option['begintime'];
        $ordername = $option['ordername'];
        $ordertel = $option['ordertel'];
        $contacttel = $option['contacttel'];
        $tnum = $option['tnum'];
        $remoteorder = $option['remoteorder'];
        $paymode = $option['paymode'];
//        $paymode = 2;//营销活动的订单的支付方式设置为2使用供应商可用金额支付——2015年7月6日17:12:54
        //订单类型，normalOrder=>普通订单，linkOrder=>联票订单，packageOrder=>套票订单
        $orderType = 'normalOrder';
        $p_info = $this->p->pInfo();
//        $ptitle = $p_info['ltitle'].$p_info['ttitle'];
        $endtime = ($p_info['delaydays'] - 1) < 0 ? 0 : ($p_info['delaydays'] - 1);
        $time = strtotime($begintime) + $endtime * 24 * 3600;
        $endtime = date("Y-m-d", $time);
        $begintime .= " 00:00:00";
        $endtime .= " 23:59:59";

        /*产品预订检查*/
        $totalMoney = 0;
        $sql = "SELECT account FROM pft_member WHERE id=$member LIMIT 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $account =  $GLOBALS['le']->f('account');
        // 新接口获取
        //零售价
        $ls_price = $this->p->tPrice_n(self::IS_SALE, $begintime, $aid, '', $account);
        //取结算价
        $tprice   = $this->p->tPrice_n(0, $begintime, $aid, '', $account );
        //结算价:100,3385,
        write_logs("结算价:$tprice,$aid,$account, {$_SESSION['account']}", '/var/www/html/wx/debug.txt');
        if (is_array($tprice)) {
            throw new DisOrderException($tprice['msg']);
        }

        //优惠金额
        if ($dataMark['discount_type']==0){
            $money_save = $dataMark['discount'];
        }
        else {
            //百分比
            $money_save = $ls_price - ($ls_price * $dataMark['discount'] / 100 / 10);
        }
        $total_money_save = ($ls_price - $money_save) * $tnum;//价格需要用零售价
        //营销活动的订单的支付方式设置为2使用供应商可用金额支付——2015年7月6日
        if ( $total_money_save==0 ) {
            $paymode = 2;
        }
        $totalTprice = $tprice * $tnum;
        $totalMoney += $totalTprice;

        //$series用来记录活动信息，json格式
        $money_save_yuan = $money_save / 100;
        $series = <<<JSON
            {"flag":"MARKETING","m_id":"{$dataMark['m_id']}","money_save":"{$money_save}","total_fee":"$total_money_save","memo":"营销活动优惠票,每张票优惠:{$money_save_yuan}元"}
JSON;
        $option['memo'] .= "营销活动优惠票,每张票优惠:{$money_save_yuan}元";

        $pcode = 0;
        $ordermode = isset($option['ordermode']) ? $option['ordermode'] : $this->ordermode;
        if ($p_info['p_type'] == "B" ) { /*线路产品额外信息*/
            throw new DisOrderException("抱歉，线路产品无法参与优惠活动");
//            $playdateStr = explode("-", substr($begintime, 0, 10));
//            $playdateStr = substr($playdateStr[0], 2, 2) . $playdateStr[1] . $playdateStr[2];
//            $series = preg_replace('/{fck_date}/', $playdateStr, $p_info['series_model']); //团号
//            $assembly = abs($_REQUEST['assembly']); //集合地点
        }
//        $proInfos=array();
        $c_infos = array();
        if ($p_info['p_type'] == "C") { //酒店按联票产品下单
            $leavetime = $option['leavetime'];
            $days = ceil((strtotime($leavetime) - strtotime($begintime)) / 24 / 3600);
            $orderType = $days > 1 ? 'linkOrder' : 'normalOrder';
            for ($n = 1; $n < $days; $n++) {
                try {
                    $date = date("Y-m-d", strtotime($begintime) + 3600 * 24 * $n);
                    $starttime = $date . " 00:00:00";
                    // $c_tprice=$cpro->tPrice($member,$begintime,$this->sale);
                    $c_tprice = $this->p->tPrice_n(self::IS_SALE, $starttime, $aid,
                        null, $account);
                    // 新接口
                    $c_tnum = $tnum;
                    $endtime = $date . " 23:59:59";
                    $c_infos[] = array(
                        "member" => $member,
                        "tprice" => $c_tprice, "tnum" => $c_tnum,
                        "ltitle" => $p_info['ltitle'],
                        "ttitle" => $p_info['ttitle'],
                        "pid" => $p_info['pid'],
                        "lid" => $p_info['lid'],
                        "tid" => $p_info['tid'],
                        "begintime" => $starttime,
                        "endtime" => $date . " 23:59:59",
                        "storage" => $p_info['storage'],
                        "storage_open" => $p_info['storage_open'],
                        "salerid" => $p_info['salerid'],
                        "ordername" => $ordername,
                        "ordertel" => $ordertel,
                        "paymode" => $paymode,
                        "ordermode" => $ordermode,
                        "apply_did" => $p_info['apply_did'],
                        "sapply_did" => $p_info['sapply_did'],
                        "contacttel" => $option['contacttel'],
                    );
                    $totalMoney += ($c_tprice - $money_save) * $c_tnum;
                } catch (Exception $e) {
                }
            }
        }
        elseif ($p_info['p_type'] == "F") { //套票产品
            $pcode = 1;
            $orderType = 'packageOrder';
            //套票判定 Author:CGP
            $bt = substr($begintime, 0, 10);
            $chk_ret = \pft\Prod\Sale::PackageTicketCheck($s, $pid, $member, $aid,
                $bt, $tnum);
            if ($chk_ret['code'] !== 200) {
                $msg = $chk_ret['code'] > 908 ? "子票【{$chk_ret['pid']}】" : '';
                throw new DisOrderException($msg . $chk_ret['msg']);
            }
        }

        $smsSendAfterOrder = 0; //下单后发送短信0不发送1发送
        $smsSendWithOrder = 1; //下单并发送短信0发送1不发送
        $no_wx_notify = false;
        $isLnkOrder = count($c_infos); //是否联票订单
        $proInfos = $isLnkOrder ? $c_infos : array(); //联票购买
        $toProvider = 1;
        if($paymode==1){
            $toProvider = 0;
        }
        if ($paymode == 1 || $p_info['sendVoucher'] == 1) {
            //未支付或特殊设置不发送短信
            $no_wx_notify = true;
        } elseif ($isLnkOrder || $p_info['p_type'] == 'C') {
            //联票订单或酒店订单，下单后发送短信
            $smsSendAfterOrder = 1;
        } else {
            //跟随订单一起发送短信
            $smsSendWithOrder = 0;
        }


        $proInfos[] = array(
            "member" => $member,
            "tprice" => $tprice,
            "tnum" => $tnum,
            "ltitle" => $p_info['ltitle'],
            "ttitle" => $p_info['ttitle'],
            "pid" => $p_info['pid'],
            "tid" => $p_info['tid'],
            "begintime" => $begintime,
            "endtime" => $endtime,
            "storage" => $p_info['storage'],
            "storage_open" => $p_info['storage_open'],
            "sapply_did" => $p_info['sapply_did']
        );

        $this->orderCheck($option, $p_info); //预订判定
        //TODO::如果是零售（散客购买),就不判断购买权限，反正都是用零售价
//        if (!$this->sale) {
//            $this->authCheck($proInfos, $aid); //购买权限判定
//        }

        $this->storageCheck($proInfos); //库存判定
        $this->payCheck($totalMoney); //金额判定
        $r = $s->Group_Order_Submit($member, $p_info['lid'], $p_info['tid'],
            $begintime, $endtime, $tprice, $tnum, $totalTprice, $ordername,
            $ordertel, "$contacttel", $p_info['salerid'], $p_info['sapply_did'],
            $paymode, $ordermode, "$remoteorder", "$assembly", "$series",
            $smsSendWithOrder, 0, $pcode, $option['sfz']);

        $log = <<<LOG
 $r = $s->Group_Order_Submit($member, {$p_info['lid']}, {$p_info['tid']},
            $begintime, $endtime, $tprice, $tnum, $totalTprice, $ordername,
            $ordertel, "$contacttel", {$p_info['salerid']}, {$p_info['sapply_did']},
            $paymode, $ordermode, "$remoteorder", "$assembly", "$series",
            $smsSendWithOrder, 0, $pcode, {$option['sfz']});
LOG;
//            write_logs($log ,'/var/www/html/wx/debug.txt');


        $sendRut  = '';
        $redirect = 0;
        if ($r >= 100000) {
            //如果总价是0的(优惠活动)，将支付状态修改为已支付——2015年7月6日14:47:49
            if ($total_money_save == 0) {
                $s->Mod_Order_Status($r, 1);
                $redirect = 1;
            }
            /*附属产品下单*/
            if ($isLnkOrder) {
                $this->subOrder($c_infos, $r);
            }
            //短信通知
//            global $aid;
//            $aid = $dataMark['fid'];
            $sql = "SELECT appid FROM pft_wx WHERE fid={$dataMark['fid']} LIMIT 1";
//            write_logs($sql ,'/var/www/html/wx/debug.txt');
            $GLOBALS['le']->query($sql);
            $row = $GLOBALS['le']->fetch_assoc();
            if ($row) {
                define('DEFAULT_WECHAT_APPID', $row['appid']);
            }
            include '/var/www/html/new/d/class/OrderSmsManual.class.php';
            $smsManual = new \PFT\SMS\OrderSmsManual($s);
            $smsManual->SetParam($ordertel, $aid, $member, $p_info['tid'],
                $pid, $r, $p_info['lid']);
            //通知顾客-微信
            if(!$no_wx_notify || $total_money_save==0 ) {
                $wx_open_id = !empty($_SESSION['openid']) ? $_SESSION['openid'] :
                    $smsManual->WxNotifyChk($member, 0, true);
//                exit;
                if ($wx_open_id) {
                    write_logs('openid='.$wx_open_id . 'aid='.$aid.'appid=' . WECHAT_APPID,'/var/www/html/wx/debug.txt');

                    $itemData = '';
                    foreach($proInfos as $prod) {
                        $itemData .= "\n{$prod['ttitle']}:{$prod['tnum']} 张；";
                    }
                    $ret = $smsManual->WxNotifyCustomer(
                        $wx_open_id,
                        date('Y-m-d H:i:s'),
                        $ordername,
                        $p_info['ltitle'],
                        $itemData,
                        $r,
                        $totalTprice / 100
                    );
                    write_logs('ret='.json_encode($ret),'/var/www/html/wx/debug.txt');
                }

            }
            if ($smsSendAfterOrder == 1) {
                $sms_ret = $smsManual->Send($p_info['ltitle'] . $p_info['ttitle'],
                    $tnum, $begintime, $endtime, $p_info['p_type']);
                if ($sms_ret != 100) {
                    self::log_result("短信发送失败|订单号[$r]|错误代码[{$sms_ret}]", '/var/www/html/new/d/logs/debug.txt');
//                    Log::writeLog("短信发送失败|订单号[$r]|错误代码[{$sms_ret}]", Log::ERROR_LOG_PATH);
                    $this->errHandle("短信发送失败[{$sms_ret}]", $r);
                }
            }

//            //通知供应商
            if ($toProvider==1) {
                if ($p_info['p_type'] == 'C') {
                    $smsManual->SmsToApplyErHotel($ordername,
                        $p_info['ltitle'] . $p_info['ttitle'],
                        $tnum, $begintime, $endtime, $r, $option['memo']);
                } else {
//                    self::log_result('发送供应商短信通知', '/var/www/html/new/d/logs/debug.txt');
                    $smsManual->OrderNotify('AFTER_SUBMIT', $proInfos, $ordername,
                        $r, $ordertel, $option['memo']);
                }
            }
            /*记录订单额外信息*/
            $this->appendInfo($r, $option);
            return array(
                'orderNum'  => $r,
                'orderType' => $orderType,
                'sendRut'   => $sendRut,
                'redirect'  => $redirect,
            );
        } else {
            $this->errHandle("下单接口出错", $r);
        }
    }
}